$.ajax({
  type: 'get',
  url: '/posts',
  success: function (response) {
    const html = template('postsTpl', {
      data: response
    });
    $('#postsBox').html(html);
    const page = template('pageTpl', {
      data: response
    });
    $('#pageBox').html(page);
  }
})


function changePage(page) {
  $.ajax({
    type: 'get',
    url: '/posts',
    data: {
      page
    },
    success: function (response) {
      const html = template('postsTpl', {
        data: response
      });
      $('#postsBox').html(html);
      const page = template('pageTpl', {
        data: response
      });
      $('#pageBox').html(page);
    }
  })
}

// 获取分类
$.ajax({
  type: 'get',
  url: '/categories',
  success: function (response) {
    const html = template('categoryTpl', {
      data: response
    });
    $('#categoryBox').html(html);
  }
})

// 筛选
$('#filterForm').on('submit', function () {
  const formData = $(this).serialize();
  $.ajax({
    type: 'get',
    url: '/posts',
    data: formData,
    success: function (response) {
      const html = template('postsTpl', {
        data: response
      });
      $('#postsBox').html(html);
      const page = template('pageTpl', {
        data: response
      });
      $('#pageBox').html(page);
    }
  })
  return false;
})

// 文章删除操作
$('#postsBox').on('click', '.delete', function() {
  if(confirm('您确认要删除该文章吗')) {
    const id = $(this).attr('data-id');
    $.ajax({
      type: 'delete',
      url: '/posts/' + id,
      success: function  () {
        location.reload();
      }
    })
  }
})